var express = require("express");
var router = express.Router();
var { tokenShortAll } = require("../model/gyq");
var db = require("../model/db");

class GetToken {
  getToken(username, time) {
    return tokenShortAll.en({ username }, time);
  }
  isToken(token) {
    return tokenShortAll.de(token);
  }
}
let Token = new GetToken();

function isReturn(token, data) {
  let TokenData = Token.isToken(token);
  switch (TokenData.code) {
    case 200:
      return {
        code: 200,
        data: data,
      };
    case 300:
      return {
        code: 300,
      };
    default:
      return {
        code: 405,
      };
  }
}

router.post("/getToken", (req, res) => {
  let { username, password } = req.body;
  console.log(username, password);
  // select * from Users WHERE phone='${username}' AND password='${password}'
  // 验证用户名和密码
  let sql = `SELECT * FROM Users WHERE phone='${username}' AND password='${password}'`;
  db.query(sql,(err, data) => {
    console.log(err,data);
      if (data.length != 0) {
        return res.send({
          code: 200,
          data: {
            tokenShort: Token.getToken({ username }, "10s"),
            tokenLong: Token.getToken({ username }, "20s"),
          },
          msg: "Token",
        });
      }else{
        return res.send({
          code: 405,
          msg: "用户名或密码错误",
        });
      }
    }
  );
});

router.post("/getData", (req, res) => {
  let token = req.headers.authorization.split(" ")[1];
  let dataAll = {
    list: [1, 2, 3, 4, 5, 6],
  };
  res.send(isReturn(token, dataAll));
});

router.post("/updateToken", (req, res) => {
  let token = req.headers.authorization.split(" ")[1];
  let username = req.body.username;
  let dataAll = Token.getToken({ username }, "10s");
  res.send(isReturn(token, dataAll));
});

// 注册表
router.post("/register", async (req, res) => {
  const { username, newpwd } = req.body;
  let sql = "select * from Users where phone = ?";
  db.query(sql, username, (error, result) => {
    if (result.length != 0) {
      res.send({
        code: 200,
        msg: "此账号已被注册",
      });
    } else {
      let insertsql = "insert into Users(phone,password) values(?,?)";
      let addParams = [username, newpwd];
      db.query(insertsql, addParams, (error, result) => {
        res.send({
          code: 200,
          msg: "注册成功",
        });
      });
    }
  });
});

router.post("/setPwd", (req, res) => {
  let { phone, newpwd } = req.body;
  console.log(phone, newpwd);
  let sql = 'update Users set password = "' + newpwd + '" where phone = "' + phone + '"';
  db.query(parametersql, () => {
    res.send({
      code: 200,
      msg: "密码设置成功",
    });
  });
});

// router.get("/indexToken", (req, res) => {
//   let q = `select * from user`;
//   db.query(q, (data) => {
//     res.send({
//       msg: data,
//     });
//   });
// });

module.exports = router;
